package cn.topcodes.tcsf.admin.service.ops;

import cn.topcode.unicorn.utils.JsonUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcode.unicorn.utils.http.HttpResp;
import cn.topcode.unicorn.utils.http.HttpUtil;
import cn.topcodes.tcsf.admin.service.licence.LicenceService;
import cn.topcodes.tcsf.admin.service.org.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Properties;

/**
 * Created by Unicorn on 2018/6/22.
 */
@Component
public class OpsConnectedListener implements ApplicationListener<OpsConnectedEvent> {

    public static final String SUBMIT_PROPERTY_URL = "http://%s:%d/api/server/submit-property";

    private boolean isPropertySubmited = false;

    private Integer httpPort;

    private String version;

    private String contextPath;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LicenceService licenceService;

    @Autowired
    private OpsService opsService;


    @Scheduled(cron = "0 0 0 * * ? ")
    public void clear() {
        opsService.clearSubmit();
        this.isPropertySubmited = false;
    }

    @Override
    public void onApplicationEvent(OpsConnectedEvent event) {
        if(!isPropertySubmited) {
            if(httpPort != null) {
                boolean success = submit(event.getNo(), event.getOpsServerHost(), event.getOpsServerHttpPort());
                if(success) {
                    return;
                }
            }
            throw new IllegalStateException("提交失败");
        }
    }

    public boolean submit(String no, String host, int port) {
        Properties props=System.getProperties();
        String osName = props.getProperty("os.name");
        String osArch = props.getProperty("os.arch");
        String osVersion = props.getProperty("os.version");

        SubmitProperty property = new SubmitProperty();
        property.setNo(no);
        property.setContextPath(contextPath);
        property.setPlatform(osName + "-" + osArch + "-" + osVersion);
        property.setHttpPort(httpPort);
        property.setVersion(version);
        property.setSysUserCount(this.sysUserService.countAll());
        property.setMachineCode(licenceService.getMatchineCode());
        property.setRegisterCode(licenceService.getRegisterCode());

        String url = String.format(SUBMIT_PROPERTY_URL, host, port);
        HttpResp httpResp = HttpUtil.post(property, url);
        if(httpResp.getStatusCode() == 200) {
            String json = httpResp.getBody();
            SubmitResult result =  JsonUtil.parse(json, SubmitResult.class);
            if(result != null && "OK".equals(result.getCode())) {
                isPropertySubmited = true;
                return true;
            }
        }
        return false;
    }

    public void setHttpPort(Integer httpPort) {
        this.httpPort = httpPort;
    }

    public void setVersionFilePath(String versionFilePath) {
        if(StringUtil.isNotBlank(version)) {
            return;
        }
        File file = new File(versionFilePath);
        if(!file.exists() || !file.isFile()) {
            return;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = reader.readLine();
            String version = line.replace("#### 当前版本：", "").trim();
            this.version = version;
        } catch (Exception e) {

        }finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {}
            }
        }
    }

    public String getVersion() {
        return version;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public String getContextPath() {
        return contextPath;
    }
}
